import { useState, useEffect, useCallback, createContext, useContext } from 'react';
    import useLocalStorage from './useLocalStorage';
    import useApi from './useApi';

    // 创建认证上下文
    const AuthContext = createContext(null);

    /**
     * 认证提供者组件
     * 提供认证状态和方法给子组件
     */
    export const AuthProvider = ({ children }) => {
      const [user, setUser, removeUser] = useLocalStorage('user', null);
      const [token, setToken, removeToken] = useLocalStorage('authToken', null);
      const [isAuthenticated, setIsAuthenticated] = useState(!!token);
      const api = useApi();

      // 当token变化时更新认证状态
      useEffect(() => {
        setIsAuthenticated(!!token);
      }, [token]);

      /**
       * 登录方法
       * @param {string} email - 用户邮箱
       * @param {string} password - 用户密码
       * @returns {Promise<Object>} 登录结果
       */
      const login = useCallback(async (email, password) => {
        try {
          // 在实际应用中，这里会调用API进行登录
          // const response = await api.post('/auth/login', { email, password });
          
          // 模拟登录成功
          const mockResponse = {
            user: {
              id: '1',
              name: '测试用户',
              email,
              avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
            },
            token: 'mock-jwt-token-' + Math.random().toString(36).substring(2),
          };
          
          setUser(mockResponse.user);
          setToken(mockResponse.token);
          return { success: true, user: mockResponse.user };
        } catch (error) {
          console.error('登录失败:', error);
          return { success: false, error: error.message || '登录失败，请重试' };
        }
      }, [api, setUser, setToken]);

      /**
       * 注册方法
       * @param {Object} userData - 用户数据
       * @returns {Promise<Object>} 注册结果
       */
      const register = useCallback(async (userData) => {
        try {
          // 在实际应用中，这里会调用API进行注册
          // const response = await api.post('/auth/register', userData);
          
          // 模拟注册成功
          const mockResponse = {
            user: {
              id: '1',
              name: userData.name,
              email: userData.email,
              avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
            },
            token: 'mock-jwt-token-' + Math.random().toString(36).substring(2),
          };
          
          setUser(mockResponse.user);
          setToken(mockResponse.token);
          return { success: true, user: mockResponse.user };
        } catch (error) {
          console.error('注册失败:', error);
          return { success: false, error: error.message || '注册失败，请重试' };
        }
      }, [api, setUser, setToken]);

      /**
       * 登出方法
       */
      const logout = useCallback(() => {
        removeUser();
        removeToken();
      }, [removeUser, removeToken]);

      /**
       * 更新用户信息
       * @param {Object} userData - 新的用户数据
       */
      const updateUser = useCallback((userData) => {
        setUser(prevUser => ({ ...prevUser, ...userData }));
      }, [setUser]);

      /**
       * 检查用户是否有特定权限
       * @param {string} permission - 权限名称
       * @returns {boolean} 是否有权限
       */
      const hasPermission = useCallback((permission) => {
        // 在实际应用中，这里会检查用户的权限列表
        // 简单起见，这里假设所有已登录用户都有所有权限
        return isAuthenticated;
      }, [isAuthenticated]);

      // 提供认证上下文给子组件
      const value = {
        user,
        token,
        isAuthenticated,
        login,
        register,
        logout,
        updateUser,
        hasPermission,
      };

      return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
    };

    /**
     * 使用认证上下文的Hook
     * @returns {Object} 认证上下文
     */
    export const useAuth = () => {
      const context = useContext(AuthContext);
      if (!context) {
        throw new Error('useAuth must be used within an AuthProvider');
      }
      return context;
    };

    export default useAuth;
